package org.example.controller;


import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.example.common.JsonResult;
import org.example.dto.bankcard.*;
import org.example.entity.BankCardIntroduceEntity;
import org.example.entity.BankFormFiledInfosEntity;
import org.example.enums.BankCardTypeEnums;
import org.example.exception.BizException;
import org.example.service.BankCardIntroduceService;
import org.example.service.BankFormFiledInfosService;
import org.example.service.BankService;
import org.example.service.utils.Constant;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 卡种类介绍信息 前端控制器
 * </p>
 *
 * @author puqingwen
 * @since 2024-03-18
 */
@Api(tags = "银行卡信息")
@Slf4j
@RestController
@RequestMapping("/bankCardIntroduce")
public class BankCardIntroduceController {


    @Autowired
    private BankService bankService;

    @Autowired
    private BankCardIntroduceService bankCardIntroduceService;

    @Autowired
    private BankFormFiledInfosService bankFormFiledInfosService;


    // 显示的星星数量
    Integer baseStartCount = 5;

    @ApiOperation("获取列表")
    @GetMapping("/queryBankCardList")
    public JsonResult<List<QueryBankCardListRespDTO>> queryBankCardList() {
        log.info("查询列表");

        return Optional.of(this.bankService.list()
                .stream().map(s -> {
                    Integer successRate = s.getSuccessRate();
                    QueryBankCardListRespDTO queryBankCardListRespDTO = new QueryBankCardListRespDTO();
                    BeanUtils.copyProperties(s, queryBankCardListRespDTO);

                    String successRateStr = this.getRate(successRate, baseStartCount);
                    queryBankCardListRespDTO.setSuccessRate(successRateStr);
                    return queryBankCardListRespDTO;
                })
                .collect(Collectors.toList()))
                .map(JsonResult::ok)
                .get();
    }

    /**
     * 获取比例
     *
     * @param successRate
     * @param baseStartCount
     * @return
     */
    public String getRate(Integer successRate, Integer baseStartCount) {
        String successRateStr = "0";
        if (null != successRate) {
            if (successRate > 100) {
                successRate = 100;
            }
            if (successRate < 0) {
                successRate = 0;
            }
            BigDecimal bigDecimal = new BigDecimal(successRate);
            bigDecimal = bigDecimal.multiply(new BigDecimal(baseStartCount)).divide(new BigDecimal(100));
            successRateStr = bigDecimal.setScale(1, RoundingMode.HALF_UP).toString();
        }
        return successRateStr;
    }

    @ApiOperation("获取详情信息")
    @GetMapping("/queryBankInfo/{id}")
    public JsonResult<QueryBankInfoRespDTO> queryBankInfo(@PathVariable Long id) {
        log.info("获取详情");
        return Optional.ofNullable(this.bankService.getById(id))
                .map(bankInfo -> {
                    // 银行名称
                    String name = bankInfo.getName();
                    String bankIcon = bankInfo.getBankIcon();
                    Integer successRate = bankInfo.getSuccessRate();
                    String rate = this.getRate(successRate, baseStartCount);
                    Map<BankCardTypeEnums, List<QueryBankIntroduceRespDTO>> typeInfoMap = this.bankCardIntroduceService.lambdaQuery()
                            .eq(BankCardIntroduceEntity::getCardId, id)
                            .in(BankCardIntroduceEntity::getType, BankCardTypeEnums.getIntroduceInfos())
                            .list()
                            .stream()
                            .sorted(Comparator.comparing(BankCardIntroduceEntity::getSort))
                            .collect(Collectors.groupingBy(BankCardIntroduceEntity::getType,
                                    Collectors.mapping(s -> QueryBankIntroduceRespDTO.builder().val(s.getInfoVal()).build(), Collectors.toList())));

                    return QueryBankInfoRespDTO.builder()
                            .bankName(name)
                            .picUrl(bankIcon)
                            .successRate(rate)
                            .bankCardKid(typeInfoMap.get(BankCardTypeEnums.CARD_KIND))
                            .askFor(typeInfoMap.get(BankCardTypeEnums.ASK_FOR))
                            .information(typeInfoMap.get(BankCardTypeEnums.INFORMATION))
                            .flow(typeInfoMap.get(BankCardTypeEnums.FLOW))
                            .customerService(typeInfoMap.get(BankCardTypeEnums.CUSTOMER_SERVICE))
                            .build();

                })
                .map(JsonResult::ok)
                .orElseThrow(() ->
                        new BizException("数据不存在")
                );
    }

    @ApiOperation("获取现场开户信息")
    @GetMapping("/queryLocale/{id}")
    public JsonResult<QueryLocaleRespDTO> queryLocale(@PathVariable Long id) {
        log.info("获取详情");
        return Optional.ofNullable(this.bankService.getById(id))
                .map(bankInfo -> {
                    // 银行名称
                    String name = bankInfo.getName();
                    String bankIcon = bankInfo.getBankIcon();
                    Map<BankCardTypeEnums, List<QueryBankIntroduceRespDTO>> typeInfoMap = this.bankCardIntroduceService.lambdaQuery()
                            .eq(BankCardIntroduceEntity::getCardId, id)
                            .in(BankCardIntroduceEntity::getType, BankCardTypeEnums.getLocaleInfos())
                            .list()
                            .stream()
                            .sorted(Comparator.comparing(BankCardIntroduceEntity::getSort))
                            .collect(Collectors.groupingBy(BankCardIntroduceEntity::getType,
                                    Collectors.mapping(s ->
                                            QueryBankIntroduceRespDTO
                                                    .builder()
                                                    .val(s.getInfoVal())
                                                    .valComment(s.getValComment())
                                                    .build(),
                                            Collectors.toList())
                            ));

                    return QueryLocaleRespDTO.builder()
                            .bankName(name)
                            .picUrl(bankIcon)
                            .businessTime(typeInfoMap.get(BankCardTypeEnums.BUSINESS_TIME))
                            .reserveType(typeInfoMap.get(BankCardTypeEnums.RESERVE_TYPE))
                            .branchBank(typeInfoMap.get(BankCardTypeEnums.BRANCH_BANK))
                            .build();

                })
                .map(JsonResult::ok)
                .orElseThrow(() -> new BizException("数据不存在"));
    }

    @ApiOperation("获取开户类型")
    @GetMapping("/queryOpenTypes/{bankId}")
    public JsonResult queryOpenTypes(@PathVariable Long bankId) {
        log.info("获取开户类型:{}", bankId);
        return Optional.of(this.bankCardIntroduceService.lambdaQuery()
                .eq(BankCardIntroduceEntity::getCardId, bankId)
                .eq(BankCardIntroduceEntity::getType, BankCardTypeEnums.SUPPORT_OPEN_TYPE)
                .list()
                .stream()
                .map(s -> QueryOpenTypesRespDTO.builder()
                        .typeId(s.getId() + "")
                        .name(s.getInfoVal())
                        .build()
                )
                .collect(Collectors.toList()))
                .map(JsonResult::ok)
                .orElseGet(() -> JsonResult.ok(new ArrayList<>()));
    }

    //    @GetMapping("/queryFormInfos/{bankId}")
    public JsonResult<List<QueryFormInfosRespDTO>> queryFormInfos(@PathVariable Long bankId, Long openTypeId) {
        log.info("获取表单字段信息:{},{}", bankId, openTypeId);

        Function<BankFormFiledInfosEntity, QueryFormInfosRespDTO> filter = d -> QueryFormInfosRespDTO.builder()
                .fieldKey(d.getFormFiled())
                .fieldName(d.getFormFiledName())
                .isRequire(d.getIsRequire())
                .formType(d.getFormType())
                .build();

        return Optional.ofNullable(this.bankFormFiledInfosService.lambdaQuery()
                .eq(BankFormFiledInfosEntity::getBankId, bankId)
                .list())
                .map(s -> {
                    if (s.size() == 0) {
                        return null;
                    }
                    return s.stream()
                            .map(filter)
                            .collect(Collectors.toList());

                })
                .map(JsonResult::ok)
                .orElseGet(() ->
                        Optional.ofNullable(Optional.ofNullable(this.bankFormFiledInfosService.lambdaQuery()
                                .eq(BankFormFiledInfosEntity::getIsBase, Constant.ONE)
                                .list()
                                .stream()
                                .map(filter)
                                .collect(Collectors.toList()))
                                .orElseGet(ArrayList::new))
                                .map(JsonResult::ok)
                                .orElse(null)

                );
    }

    //    @ApiOperation("获取下拉输入框")
//    @GetMapping("/querySelectList/{bankId}")
    public JsonResult querySelectList(@PathVariable Long bankId, @RequestParam String formKey) {
        log.info("获取下拉输入框:{},{}", bankId, formKey);
        return null;
    }

}

